package vooga.util;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.File;
import java.util.Enumeration;
import java.util.Properties;

/**
 * This class handles Propeties, allowing the updating and .properties files
 * This throws IOExceptions if file is not found or can not be read or written
 * when needed.  Multiple threads can use the same file.
 * @author Jonathan Odom and Andrew Kim
 *
 */


public class PropertiesManager {
	
	private Properties myPropertyFile;
	private String myFileName;
	private FileOutputStream myFileOut;
	private FileInputStream myFileIn;
	private File myBuildFile;
	
	public PropertiesManager (Object target) throws IOException
	{
		myFileName = "resources/" + getClassName(target) + ".properties";
		myPropertyFile = new Properties();
		myBuildFile = new File(myFileName);
		if(!(myBuildFile.exists()))
		{
			myBuildFile.createNewFile();
		}
		myFileIn = new FileInputStream(myFileName);
		myPropertyFile.load(myFileIn);
		myFileIn.close();
	}
	
	public PropertiesManager (String s) throws IOException
	{
		myFileName = "resources/" + s + ".properties";
		myPropertyFile = new Properties();
		myBuildFile = new File(myFileName);
		if(!(myBuildFile.exists()))
		{
			myBuildFile.createNewFile();
		}
		myFileIn = new FileInputStream(myFileName);
		myPropertyFile.load(myFileIn);
		myFileIn.close();
	}
	
	public String getString(String key)
	{
		try{
			myFileIn = new FileInputStream(myFileName);
			myPropertyFile.load(myFileIn);
			myFileIn.close();
			
		}
		catch(IOException io)
		{
			System.out.println(io.getMessage());
			return "";
		}
		return myPropertyFile.getProperty(key);
	}
		
    //sets the property and calls a store that saves it to a file
	public void setProperty(String key, String value) throws IOException
	{
		myPropertyFile.setProperty(key, value);
		updatePropertyFile();
		
	}
	
	// returns a list of all keys in the file
	public Enumeration<String> getKeys()
	{
		return (Enumeration<String>) myPropertyFile.propertyNames();
	}
	
	//removes the key and value
	public void remove(String key) throws IOException
	{
		myPropertyFile.remove((String) key);
		updatePropertyFile();
	}
	
	//removes all of the keys and values
	public void removeAll() throws IOException
	{
		myPropertyFile.clear();
		updatePropertyFile();
	}
	
	//saves the property to file and flushes the buffer
	//this must be so that multiple classes and threads can access the same data structure
	private void updatePropertyFile() throws IOException
	{

		myFileOut = new FileOutputStream(myFileName);
		myPropertyFile.store(myFileOut, "");
		myFileOut.close();
	}
	
	private String getClassName (Object target)
    {
        String classname = target.getClass().getName();
        return classname.substring(classname.lastIndexOf(".") + 1);
    }

}
